//
//  ZCAdressVC.m
//  zctx
//
//  Created by apple on 15/12/3.
//  Copyright © 2015年 sanliang. All rights reserved.
//

#import "ZCAdressVC.h"
#import "ZCAdressPickerView.h"
@interface ZCAdressVC ()<UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
{
    UITextField *adressField;
    UITextField *detailField;
}
@property (nonatomic, strong) NSArray *arrProvince;
@property (nonatomic, strong) NSArray *arrCity;
@property (nonatomic, strong) DZRegionProvinceModel *selectProvince;
@property (nonatomic, strong) DZRegionCityModel *selectCity;
@property (nonatomic, strong) UIPickerView *pickView;
@property (nonatomic, strong) UIButton *buttonConfirm;
@end

@implementation ZCAdressVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ZCAdressVC"];
    [MTA trackPageViewBegin:@"ZCAdressVC"];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ZCAdressVC"];
    [MTA trackPageViewEnd:@"ZCAdressVC"];
    self.tabBarController.hidesBottomBarWhenPushed = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"地址";
    self.view.backgroundColor = [UIColor colorWithHexString:@"#fafcfb"];
    self.arrCity = [NSArray array];
    self.arrProvince = [NSArray array];
    
    [self initnavegation];
    [self initNameView];
//    self.selectProvince = self.arrProvince[0];
    self.arrProvince = [RegionManager getAllProvinces];
    
}
-(void)initnavegation{
    
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 19, 36);
    [leftButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_leftNavBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = barButtonItem_leftNavBar;
}

-(void)backButtonPressed{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)initNameView{
    
    UIView *btnView = [[UIView alloc]init];
    [self.view addSubview:btnView];
    [btnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(64);
        make.right.equalTo(self.view).with.offset(0);
        make.left.equalTo(self.view).with.offset(0);
        make.height.mas_equalTo(@200);
    }];
    btnView.backgroundColor = [UIColor whiteColor];
    
//    UILabel *useLable = [[UILabel alloc]init];
//    useLable.text = @"地址：";
//    useLable.font = [UIFont systemFontOfSize:16];
//    [btnView addSubview:useLable];
//    [useLable mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(btnView.top).with.offset(40);
//        make.left.equalTo(btnView).with.offset(30);
//        make.height.mas_equalTo(@25);
//        make.width.mas_equalTo(@70);
//    }];
//    
//    adressField = [[UITextField alloc]init];
//    [btnView addSubview:adressField];
//    adressField.tag = 1;
//    adressField.font = [UIFont systemFontOfSize:15];
//    [adressField setBackgroundColor:[UIColor colorWithHexString:@"f2f2f2"]];
//    [adressField mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerY.equalTo(useLable.centerY);
//        make.height.mas_equalTo(@(25));
//        make.left.equalTo(useLable.right).with.offset(0);
//        make.width.mas_equalTo(@(SCREEN_WIDTH/2));
//    }];
//    adressField.delegate = self;
    
    [self.view addSubview:self.buttonProvince];
    [self.buttonProvince mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(btnView.top).with.offset(40);
        make.left.equalTo(btnView).with.offset(30);
        make.height.mas_equalTo(@25);
        make.width.mas_equalTo(@80);
    }];
    [self.view addSubview:self.buttonCity];
    [self.buttonCity mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.buttonProvince.centerY);
        make.height.mas_equalTo(@(25));
        make.left.equalTo(self.buttonProvince.right).with.offset(0);
        make.width.mas_equalTo(@80);
    }];
    detailField = [[UITextField alloc]init];
    [btnView addSubview:detailField];
    detailField.tag = 2;
    detailField.font = [UIFont systemFontOfSize:15];
    detailField.placeholder = @"请填写详细地址";
    [detailField setBackgroundColor:[UIColor colorWithHexString:@"f2f2f2"]];
    [detailField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.buttonProvince.bottom).with.offset(20);
        make.left.equalTo(btnView).with.offset(30);
        make.height.mas_equalTo(@25);
        make.width.mas_equalTo(@(SCREEN_WIDTH-60));    }];

    UIButton *okButton = [UIButton new];
    [btnView addSubview:okButton];
    [okButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(btnView.bottom).with.offset(-30);
        make.right.equalTo(btnView).with.offset(-30);
        make.left.equalTo(btnView).with.offset(30);
        make.height.mas_equalTo(@44);
    }];
    [okButton setTitle:@"确认" forState:UIControlStateNormal];
    okButton.backgroundColor = MainColor;
    okButton.layer.cornerRadius =4;
    [okButton addTarget:self action:@selector(confirmButtonClick) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark 点击确认
-(void)confirmButtonClick{
    
    if (!self.selectCity.code) {
        [[[iToast makeText:@"请选择城市"]setGravity:iToastGravityCenter] show];
        return;
    }
    if (detailField.text.length<=0) {
        [[[iToast makeText:@"请填写详细地址"]setGravity:iToastGravityCenter] show];
        return;
    }
    [NetworkManager requestModifyaddressWithMid:UserModel.mid code:self.selectCity.code address:detailField.text success:^(NSDictionary *ArrayResponse) {
        NSString *err = [NSString stringWithFormat:@"%@",[ArrayResponse objectForKey:@"err" ]];  // 1 失败 0  成功
        if ([err isEqualToString:@"0"]) {
            NSLog(@"成功");
            
            [[[iToast makeText:@"修改成功"]setGravity:iToastGravityCenter] show];
              [[NSNotificationCenter defaultCenter]postNotificationName:@"userinfo" object:nil userInfo:@{@"user":@"4"}];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            NSLog(@"操作失败");
            NSString *msg = [NSString stringWithFormat:@"%@",[ArrayResponse objectForKey:@"msg" ]];
            [[[iToast makeText:msg]setGravity:iToastGravityCenter] show];
        }
    } failure:^(NSError *error) {
        
    }];
}
//#pragma mark --- UITextFieldDelegate
//
//-(void)textFieldDidBeginEditing:(UITextField *)textField{
//    [textField resignFirstResponder];
//    ZCAdressPickerView* pikerView = [[ZCAdressPickerView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH, 260)];
//    pikerView.delegate = self;
//    [pikerView show];
//}
//
//- (void)getAddressStrPicker:(NSString *)address{
//    
//    adressField.text = address;
//}


-(void)provinceButtonClick{
    [self showPickerViewWithTag:ZCAdressTypeProvince];
}

-(void)cityButtonClick{
    if (self.selectProvince.code) {
        self.arrCity = [RegionManager getAllCitiesByProvinceCode:self.selectProvince.code];
        [self showPickerViewWithTag:ZCAdressTypeCity];
    } else {
        [self showPickerViewWithTag:ZCAdressTypeProvince];
    }
}

- (void)showPickerViewWithTag:(ZCAdressType)type {
    if (self.pickView && self.buttonConfirm) {
        [self.pickView removeFromSuperview];
        [self.buttonConfirm removeFromSuperview];
    }
    self.pickView = nil;
    self.pickView.tag = type;
    [self.view addSubview:self.pickView];
    [self.pickView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.bottom).with.offset(-50);
        make.height.mas_equalTo(216);
        make.left.mas_equalTo(0);
        make.width.equalTo(self.view.width);
    }];
    self.buttonConfirm = nil;
    self.buttonConfirm.tag = type;
    [self.view addSubview:self.buttonConfirm];
    [self.buttonConfirm mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.bottom);
        make.height.mas_equalTo(50);
        make.left.mas_equalTo(0);
        make.width.equalTo(self.view.width);
    }];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (pickerView.tag == ZCAdressTypeProvince) {
        return self.arrProvince.count;
    } else if (pickerView.tag == ZCAdressTypeCity) {
        return self.arrCity.count;
    }
    return 0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (pickerView.tag == ZCAdressTypeProvince) {
        DZRegionProvinceModel *model = self.arrProvince[row];
        return model.name;
    } else if (pickerView.tag == ZCAdressTypeCity) {
        DZRegionCityModel *model = self.arrCity[row];
        return model.name;
    }
    return @"";
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

#pragma mark 地址确认按钮

- (void)confirmButtonClick:(UIButton *)button {
    [self.pickView removeFromSuperview];
    [self.buttonConfirm removeFromSuperview];
    
    if (button.tag == ZCAdressTypeProvince) {
        [self.buttonCity setTitle:@"城市" forState:UIControlStateNormal];
        self.selectCity = nil;
        DZRegionProvinceModel *model = [self.arrProvince objectAtIndex:[self.pickView selectedRowInComponent:0]];
        self.selectProvince = model;
        [self.buttonProvince setTitle:model.name forState:UIControlStateNormal];
    } else {
        DZRegionCityModel *modelcity = [self.arrCity objectAtIndex:[self.pickView selectedRowInComponent:0]];
        self.selectCity = modelcity;
        [self.buttonCity setTitle:self.selectCity.name forState:UIControlStateNormal];
    }
    NSLog(@"self.selectProvive.code = %@ , self.city.code = %@",self.selectProvince.code,self.selectCity.code);
}


- (UIButton *)buttonProvince {
    if (!_buttonProvince) {
        _buttonProvince = [UIButton buttonWithType:UIButtonTypeCustom];
        [_buttonProvince setTitle:@"省份" forState:UIControlStateNormal];
        [_buttonProvince setTitleColor:[UIColor colorWithHexString:@"666666"] forState:UIControlStateNormal];
        _buttonProvince.titleLabel.font = [UIFont systemFontOfSize:15];
        [_buttonProvince setImage:[UIImage imageNamed:@"raise_san"] forState:UIControlStateNormal];
        [_buttonProvince.imageView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(_buttonProvince.bottom).with.offset(0);
            make.right.equalTo(_buttonProvince.right).with.offset(0);
            make.width.mas_equalTo(@(10));
            make.height.mas_equalTo(@(10));
        }];
        [_buttonProvince addTarget:self action:@selector(provinceButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _buttonProvince;
}

- (UIButton *)buttonCity {
    if (!_buttonCity) {
        _buttonCity = [UIButton buttonWithType:UIButtonTypeCustom];
        [_buttonCity setTitle:@"城市" forState:UIControlStateNormal];
        [_buttonCity setTitleColor:[UIColor colorWithHexString:@"666666"] forState:UIControlStateNormal];
        _buttonCity.titleLabel.font = [UIFont systemFontOfSize:15];
        [_buttonCity setImage:[UIImage imageNamed:@"raise_san"] forState:UIControlStateNormal];
        [_buttonCity.imageView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(_buttonCity.bottom).with.offset(0);
            make.right.equalTo(_buttonCity.right).with.offset(0);
            make.width.mas_equalTo(@(10));
            make.height.mas_equalTo(@(10));
        }];
        [_buttonCity addTarget:self action:@selector(cityButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _buttonCity;
}
- (UIPickerView *)pickView {
    if (!_pickView) {
        _pickView = [[UIPickerView alloc] init];
        [_pickView setBackgroundColor:[UIColor whiteColor]];
        _pickView.delegate = self;
    }
    return _pickView;
}

- (UIButton *)buttonConfirm {
    if (!_buttonConfirm) {
        _buttonConfirm = [UIButton buttonWithType:UIButtonTypeCustom];
        [_buttonConfirm setTitle:@"确定" forState:UIControlStateNormal];
        [_buttonConfirm setTitleColor:[UIColor colorWithHexString:@"666666"] forState:UIControlStateNormal];
        [_buttonConfirm setBackgroundColor:[UIColor whiteColor]];
        [_buttonConfirm addTarget:self action:@selector(confirmButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _buttonConfirm;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
